package com.kaifamiao.dao.impl;

import com.kaifamiao.dao.CustomerDAO;
import com.kaifamiao.entity.Customer;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.List;

public class CustomerDaoByJdbc implements CustomerDAO {

    private JdbcTemplate template;

    private RowMapper<Customer> rowMapper = new RowMapper<Customer>() {
        @Override
        public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
            Customer c = new Customer();
            c.setId( rs.getInt( "id" ) );
            c.setEmail( rs.getString( "email" ) );
            c.setTel( rs.getString( "tel" ) );
            c.setPassword( rs.getString( "password" ) );
            java.sql.Date date = rs.getDate( "birthdate" );
            if( date != null ) {
                c.setBirthdate( date.toLocalDate() );
            }
            String m = rs.getString( "married" );
            c.setMarried( "Y".equalsIgnoreCase( m ) );
            return c;
        }
    };

    @Override
    public Customer find(Integer id) {
        String sql = "SELECT email, tel, password, birthdate, married, id FROM t_customers WHERE id = ?";
        return template.queryForObject(sql, rowMapper, id);
    }

    @Override
    public List<Customer> findAll() {
        String sql = "SELECT email, tel, password, birthdate, married, id FROM t_customers ORDER BY id";
        return template.query(sql, rowMapper);
    }

    @Override
    public int persist(Customer c) {
        System.out.println( template );
        String insert = "INSERT INTO t_customers (email, tel, password, birthdate, married, id) VALUES (?, ?, ?, ?, ?, ?)";
        LocalDate b = c.getBirthdate();
        java.sql.Date date = b == null ? null : java.sql.Date.valueOf( b );
        String married = c.isMarried() ? "Y" : "N" ;
        Integer id = this.nextId();
        Object[] params = { c.getEmail(), c.getTel(), c.getPassword(), date, married, id };
        return template.update(insert, params);
    }

    private Integer nextId() {
        String sql = "SELECT IFNULL( MAX(id), 0 ) + 1 FROM t_customers";
        RowMapper<Integer> rowMapper = new RowMapper<Integer>() {
            @Override
            public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getInt( 1 );
            }
        };
        // template.queryForObject(sql, rowMapper, ...args )
        return template.queryForObject( sql, rowMapper );
    }

    @Override
    public int update(Customer c) {
        return 0;
    }

    @Override
    public int remove(Integer id) {
        return 0;
    }

    public JdbcTemplate getTemplate() {
        return template;
    }

    public void setTemplate(JdbcTemplate template) {
        this.template = template;
    }
}
